package com.example.controller;

import com.example.mapper.one.GraduateMapper;
import com.example.pojo.GraduateInfo;
import com.example.pojo.Instructor;
import com.example.pojo.Result;
import com.example.pojo.Tree;
import com.example.service.GraduateService;
import com.example.service.TreeService;
import com.example.util.ResultUtil;
import com.example.util.token.UserLoginToken;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/graduateInfo")
public class GraduateInfoContrler {

    @Resource
    private TreeService treeService;

    @Resource
    private GraduateService graduateService;

    @Resource
    private GraduateMapper graduateMapper;

    /*获取树节点*/
    @UserLoginToken
    @RequestMapping("/getTree")
    public Result getTree(){
        List<Tree> list = treeService.getChildTree(0);
        Result result = ResultUtil.success(list);
        return result;
    }

    /*获取毕业生数据*/
    @UserLoginToken
    @RequestMapping("/getGraData")
    public Map getGraData(@RequestParam(required = false) Integer grade, @RequestParam(required = false) Integer major, @RequestParam(required = false) Integer team,
                             @RequestParam(required = false) Integer sno, @RequestParam(required = false) String sname, @RequestParam(required = false) String instructor,
                             @RequestParam Integer currentPage, @RequestParam Integer pageSize){
        PageHelper.startPage(currentPage, pageSize);
        List<GraduateInfo> list = graduateMapper.getGraData(grade,major,team,sno,sname,instructor);
        PageInfo<GraduateInfo> pageInfo = new PageInfo<>(list);
        // getTotal获取总条数
        pageInfo.getTotal();
        // 获取当前页的结果集
        pageInfo.getList();
        Map resultMap = new HashMap();
        resultMap.put("total",pageInfo.getTotal());
        resultMap.put("tableData",pageInfo.getList());
//        Result result = ResultUtil.success(pageInfo.getList());
        return resultMap;
    }

    /*单个删除毕业生*/
    @UserLoginToken
    @RequestMapping("/delGra")
    public Result delGra(@RequestParam Integer snoId){
        int isDel = graduateMapper.deleteGra(snoId);
        Result result = ResultUtil.success("删除成功");
        return result;
    }


    /*批量删除毕业生*/
    @UserLoginToken
    @RequestMapping("/batchDelGra")
    public Result batchDelGra(@RequestParam String ids){
        String[] idArray=ids.split(",");
        for(int i = 0;i < idArray.length;i++){
            int id = Integer.parseInt(idArray[i]);
            int isDel = graduateMapper.deleteGra(id);
        }
        Result result = ResultUtil.success("删除成功");
        return result;
    }

    /*获取指导老师*/
    @UserLoginToken
    @RequestMapping("/getInstructor")
    public Result getInstructor(@RequestParam String grade, @RequestParam String major, @RequestParam String team){
        List<Instructor> list = graduateMapper.getInstructor(grade,major,team);
        Result result = ResultUtil.success(list);
        return result;
    }

    /*根据学号获取姓名*/
    @UserLoginToken
    @RequestMapping("querySname")
    public Result querySname(@RequestParam(required = true) Integer sNo){
        String sname = graduateMapper.querySname(sNo);
        Result result;
        if(sname != null){
            result = ResultUtil.success(sname);
        }
        else{
            result = ResultUtil.error(500,"不存在该学生");
        }
        return result;
    }

    /*增加一条毕业生信息*/
    @UserLoginToken
    @RequestMapping("/addGraInfo")
    public Result addGraInfo(@RequestBody GraduateInfo graduateInfo){
        int isAdd = graduateService.addGra(graduateInfo);
        Result result;
        switch (isAdd){
            case -3:
                result = ResultUtil.error(500,"捕捉到插入未知错误");
                break;
            case -2:
                result = ResultUtil.error(500,"该生已存在");
                break;
            case -1:
                result = ResultUtil.error(500,"该生辅导员获取失败");
                break;
            case 0:
                result = ResultUtil.error(500,"数据插入失败");
                break;
            case 1:
                result = ResultUtil.success("插入成功");
                break;
                default:
                    result = ResultUtil.error(500,"未知错误，请联系管理员");
                    break;
        }
        return result;
    }


    /*修改一条毕业生信息*/
    @UserLoginToken
    @RequestMapping("/editGraInfoById")
    public Result editGraInfoById(@RequestBody GraduateInfo graduateInfo){
        int isUpdate = graduateMapper.updateGraById(graduateInfo);
        Result result;
        if(isUpdate>0){
            result = ResultUtil.success("修改成功");
        }
        else{
            result = ResultUtil.error(500,"修改失败");
        }
        return result;
    }

    /*下载毕业生信息模板*/
    @RequestMapping("/downloadTemplate")
    public void downloadWorkHourRecordTemplate(HttpServletResponse response) {
        try {
            org.springframework.core.io.Resource resource = new ClassPathResource("templates/graInfo.xlsx");
            File file = resource.getFile();
            String filename = resource.getFilename();
            InputStream inputStream = new FileInputStream(file);
            //强制下载不打开
            response.setContentType("application/force-download");
            OutputStream out = response.getOutputStream();
            //使用URLEncoder来防止文件名乱码或者读取错误
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            int b = 0;
            byte[] buffer = new byte[1000000];
            while (b != -1) {
                b = inputStream.read(buffer);
                b = inputStream.read(buffer);
                if (b != -1) {
                    out.write(buffer, 0, b);
                }
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*上传批量导入文件*/
    @PostMapping("/importGra")
    public boolean importGra(@RequestParam(required = false,value = "grade") Integer grade, @RequestParam(required = false,value = "major") Integer major, @RequestParam(required = true,value = "team") Integer team,  @RequestParam("file") MultipartFile file) {
        boolean a = false;
        String fileName = file.getOriginalFilename();
        try {
            a = graduateService.batchImport(fileName, file, team);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  a;
    }


    /*获取所有系*/
    @UserLoginToken
    @GetMapping("/getGrade")
    public Map getGrade(){
        Map resultMap = new HashMap();
        List gradeList = treeService.getGradeList();
        resultMap.put("code",200);
        resultMap.put("gradeList",gradeList);
        return resultMap;
    }

    /*获取所有数据*/
    @UserLoginToken
    @GetMapping("/getAllData")
    public Map getAllData(@RequestParam(required = true)Integer gradeId){
        Map resultMap = new HashMap();
        resultMap = graduateService.getAllData(gradeId);
        return resultMap;
    }

}
